//
//  RAPGridPicturesView.swift
//  COPYCAT-Weibo
//
//  Created by 闫萌 on 1/6/16.
//  Copyright © 2016 RendezvousAuParadis. All rights reserved.
//

import UIKit

/// 最大列数
private let kMaxCol = 3
/// 图片cell 间距
private let kItemPadding: CGFloat = 4
/// 图片cell边长
let RAPImageCellSideLength = (kScreenBounds.width - 2 * kStatusCellMargin - 2 * kItemPadding) / CGFloat(kMaxCol)
/// cell ID
private let kCellID = "CellID"

class RAPGridPicturesView: UICollectionView, UICollectionViewDataSource, RAPGridImageCellDelegate, UICollectionViewDelegate {
    
    // MARK: - 公共方法
    ///  添加图片
    ///
    ///  - parameter image: 待添加的图片
    func addImage(image: UIImage) {
        // 如果含有9张图片，则不在添加
        if imageArray.count == 9 {
            return
        }
        
        imageArray.append(image)
        // 图片发生改变，调用闭包
        imageCountChangedClosure?(count: imageArray.count)
        // 刷新数据，不能少
        reloadData()
    }
    
    var selectedImages: [UIImage] {
        return imageArray
    }
    
    // MARK: - 自定义属性
    private lazy var imageArray: [UIImage] = [UIImage]()
    
    /// 加号按钮被点击时执行
    var addButtonClickedClosure: (() -> ())?
    
    /// 删除／添加图片时调用
    var imageCountChangedClosure: ((count: Int) -> ())?
    
    
    // MARK: - 系统方法
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        // 设置layout对象
        flowLayout.itemSize = CGSizeMake(RAPImageCellSideLength, RAPImageCellSideLength)
        flowLayout.minimumLineSpacing = kItemPadding
        flowLayout.minimumInteritemSpacing = kItemPadding
        super.init(frame: frame, collectionViewLayout: flowLayout)
        prepareToUse()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func prepareToUse() {
        backgroundColor = UIColor.clearColor()
        
        self.dataSource = self
                self.delegate = self
        self.registerClass(RAPGridImageCell.self, forCellWithReuseIdentifier: kCellID)
    }
    
    
}

// MARK: - UICollectionViewDataSource
extension RAPGridPicturesView {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //
        return (imageArray.count == 0 || imageArray.count == 9) ? imageArray.count : imageArray.count + 1
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        //
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(kCellID, forIndexPath: indexPath) as! RAPGridImageCell
        
        if imageArray.count >= 1 && imageArray.count <= 8 && indexPath.item == imageArray.count {
            cell.image = nil
        } else {
            
            cell.image = imageArray[indexPath.item]
        }
        
        cell.delegate = self
        cell.currentIndexPath = indexPath
        
        return cell
    }
}

// MARK: - RAPGridImageCellDelegate
extension RAPGridPicturesView {
    func gridImageCell(GridImageCell: RAPGridImageCell, removeButtonDidClickAtIndexPath: NSIndexPath) {
        let removedImage = imageArray.removeAtIndex(removeButtonDidClickAtIndexPath.item)
        // 图片发生改变，调用闭包
        imageCountChangedClosure?(count: imageArray.count)
        RAPLog("已删除\(removedImage)")
        reloadData()
    }
}

// MARK: - UICollectionViewDelegate
extension RAPGridPicturesView {
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        /*
        一旦cell被选中，立刻取消其选中状态，
        从而造成按下--->松开的高亮效果
        */
        deselectItemAtIndexPath(indexPath, animated: true)
        
        
        if imageArray.count >= 1 && imageArray.count <= 8 && indexPath.item == imageArray.count {
            // 如果加号按钮被选中，执行下面的闭包
            addButtonClickedClosure?()
        }

    }
    
}
